//
//  Player.m
//  MountEverestFM
//
//  Created by dllo on 15/10/29.
//  Copyright © 2015年 chenn. All ri<<ghts reserved.
//

#import "Player.h"

@implementation Player

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.audioPlayer = [[STKAudioPlayer alloc] init];
        self.audioPlayer.delegate = self;
        self.audioPlayer.meteringEnabled = YES;
        [self.audioPlayer setVolume:0.0];
        self.arr = [NSMutableArray array];
        self.playerModel.index = 0;
        _number = 0;
#warning 这个值从设置里面读取出来
//       self.isPlay = [[NSUserDefaults standardUserDefaults] boolForKey:@"isPlay"];
        self.history = NO;
    }
    return self;
}



+ (instancetype)shareInstance
{
    static Player *player = nil;
    if(player == nil){
        player = [[Player alloc] init];
        // 后台播放音频设置
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    }
    return player;
}

- (void) dataHandler
{
    if (self.playerModel.title == nil || _history == YES) {
        [self first];
    } else {
        
            [self.arr removeAllObjects];
            for (MusicModel *musicModel in self.playerModel.musicArray) {
                NSString *str = musicModel.playUrl64;
                NSLog(@"%@",str);
                [self.arr addObject:str];
            }
        MusicModel *musicModel= [_playerModel.musicArray objectAtIndex:_playerModel.index];
        [self.audioPlayer play:musicModel.playUrl64];
    
    }
}


- (void) first
{
    DBHandler *db = [DBHandler shareInstance];
    [db openDB];
    NSArray *arr = [db selectAllCollect];
    [db closeDB];
    _historyArr = [NSMutableArray array];
    if (arr.count != 0) {
        for (CollectModel *collect in arr) {
            HistoryModel *historyModel = [[HistoryModel alloc]init];
            historyModel.nickname = collect.nickname;
            historyModel.albumCoverSmall = collect.AlbumCoverSmall;
            historyModel.intro = collect.intro;
            historyModel.albumTitle = collect.albumTitle;
            
            historyModel.playUrl64 = collect.playUrl64;
            historyModel.title = collect.title;
            historyModel.coverSmall = collect.coverSmall;
            historyModel.coverLarge = collect.coverLarge;
            historyModel.rePlayTimes = collect.rePlayTime;
            [_historyArr addObject:historyModel];
        }
        
        HistoryModel *historyModel = [self.historyArr objectAtIndex:_number];
        NSLog(@"%@", _historyArr);
        NSLog(@"......%@",historyModel.playUrl64);
        [self.audioPlayer play:historyModel.playUrl64];
    }
    
}

// 播放
- (void)playFromNet
{
   
    //单例 判断波不播放
           [self dataHandler];
    
}

- (void)pause
{
    if (self.audioPlayer.state == STKAudioPlayerStatePaused ) {
        [self.audioPlayer resume];
    } else if (self.audioPlayer.state == STKAudioPlayerStatePlaying) {
        [self.audioPlayer pause];
    }
}

// 下一曲
- (void)next
{
    NSLog(@"%ld", _num);
    if (_playerModel.index < _listArr.count - 1) {
        _playerModel.index++;
        [self playFromNet];
    }
}


// 上一曲
- (void)forward
{
    if (_playerModel.index > 0) {
        _playerModel.index--;
        [self playFromNet];
    }
}

- (void)collectPreseve
{
    MusicModel *musicModel = [_playerModel.musicArray objectAtIndex:_playerModel.index];
    if (_audioPlayer.state == STKAudioPlayerStatePlaying) {
        CollectModel *collectModel = [CollectModel collectModelWithRequstUrl:_playerModel.requstUrl albumTitle:_playerModel.title AlbumCoverSmall:_playerModel.coverSmall index:_playerModel.index nickname:_playerModel.nickname intro:_playerModel.intro AlbumPlayTimes:_playerModel.playTimes playUrl64:musicModel.playUrl64 downloadUrl:musicModel.downloadUrl title:musicModel.title duration:musicModel.duration coverSmall:musicModel.coverSmall coverLarge:musicModel.coverLarge playtimes:musicModel.playtimes downloadSize:musicModel.downloadSize createdAt:musicModel.createdAt rePlayTime:[NSString stringWithFormat:@"%f", _audioPlayer.progress]];
        
        DBHandler *db = [DBHandler shareInstance];
        [db openDB];
        [db insertVideo:collectModel];
        [db updateCollect:collectModel whereTitle:musicModel.title];
        [db closeDB];
    }
}

#pragma mark - audioPlayer协议方法 - 播放结束
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    if (audioPlayer.stopReason == STKAudioPlayerStopReasonEof && _playerModel.index < _playerModel.musicArray.count - 1) {
        [self next];
    }
}

#pragma mark - audioPlayer协议方法 - 播放状态改变
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    if (state == STKAudioPlayerStatePlaying) {
        [[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:@"isPlaying"];
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        if (_history == NO) {

            [center postNotificationName:@"isPlaying" object:_playerModel userInfo:nil];
        } else {
            HistoryModel *historyModel = [self.historyArr objectAtIndex:_number];
            [center postNotificationName:@"isPlaying" object:historyModel userInfo:nil];
        }
        
    } else if (state == STKAudioPlayerStatePaused) {
        [[NSUserDefaults standardUserDefaults]setObject:@"NO" forKey:@"isPlaying"];
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        if (_history == NO) {
            [center postNotificationName:@"isPlaying" object:_playerModel userInfo:nil];
        } else {
            HistoryModel *historyModel = [self.historyArr objectAtIndex:_number];
            [center postNotificationName:@"isPlaying" object:historyModel userInfo:nil];
        }
    }
}

#pragma mark - audioPlayer协议方法 - 缓冲结束
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId
{
    
}

#pragma mark - audioPlayer协议方法 - 意外的错误
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    
}

#pragma mark - audioPlayer协议方法 - 开始播放
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId
{
    
    
}

@end